package com.bot.backend.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bot.backend.mapper.UserMapper;
import com.bot.backend.pojo.User;
import com.bot.backend.service.user.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    // 用户注册
    @Override
    public Map<String, String> register(String username, String password, String confirmedPassword) {
        Map<String, String> map = new HashMap<>();
        if (username == null) {
            map.put("error_message", "用户名不能为空");
            return map;
        }
        if (password == null) {
            map.put("error_message", "密码不能为空");
            return map;
        }

        username = username.trim(); // 删除首位空白字符
        if (username.length() == 0) {
            map.put("error_message", "用户名不能为空");
            return map;
        }
        if (username.length() > 100) {
            map.put("error_message", "用户名长度不能大于100");
        }

        if (password.length() > 100) {
            map.put("error_message", "密码长度不能大于100");
            return map;
        }

        if (password.length() == 0) {
            map.put("error_message", "密码不能为空");
            return map;
        }
        if (!password.equals(confirmedPassword)) {
            map.put("error_message", "两次密码不一致");
            return map;
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        Long selectCount = userMapper.selectCount(userQueryWrapper);
        if (selectCount > 0) {
            map.put("error_message", "用户名已存在，请重新输入");
            return map;
        }

        String encode = passwordEncoder.encode(password); // 将密码加密存入数据库
        String photo = "https://cdn.acwing.com/media/user/profile/photo/246711_md_08990849f1.png";
        User user = new User();
        user.setPassword(encode);
        user.setPhoto(photo);
        user.setUsername(username);
        user.setRating(1500);
        user.setCreateTime(new Date());
        int insert = userMapper.insert(user);
        if (insert > 0) {
            map.put("error_message", "success");
            return map;
        }

        map.put("error_message", "插入数据库失败");
        return map;
    }
}
